//------------------------------ 一站到底 ------------------------------------------------------
/**
 * 玩法 1每关题目全部答对即为过关
 *      2中间答错任何一题，显示错误UI，即当前闯关失败
 *      3当当前关卡全部答对时提示闯关成功，可继续闯关
 *      4当全部关卡通过之后，提示用户领取奖品
 */
var app = getApp();
var config = require('../../../../config.js');
var index = 0;
var timer; // 计时器
var currQuestion;
//圆形进度条 
var interval;
var varName;
var ctx = wx.createCanvasContext('canvasArcCir');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    questionList: [],
    time: 0,  //当前时长
    totalTime: 20,//总时长
    currentQuestionPos: 1,
    //服务器需要的数据集合
    answersData: [],
    rightCount: 0,
    ansError: false,
    //当前关卡进度 每次都从第一关开始
    currGatePos: 0,
    currGateId: 4,
    nickName:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    index = 0;
    this.setData({
      nickName: wx.getStorageSync('userInfo').name,
      currGatePos: 0,
      isShare:options.isShare,
      times:options.times
    });

    this.getCurrGateId();
    this.getQuestionList();

  },
  /**
   * 每次打开页面都会调用一次。
   */
  onShow: function () {


  },
  /**
   * 一个页面只会调用一次，代表页面已经准备妥当，可以和视图层进行交互。
   */
  onReady: function () {
    this.drawDefaultArc();
  },

  /**
   * 取出当前关卡的id 注意通过关卡时 把currGatePos +1
   */
  getCurrGateId: function () {
    var that = this;
    try {
      var gateList = wx.getStorageSync(config.gateList).miniGates;
      if (gateList) {
        var currGatePos = wx.getStorageSync(config.gateList).miniUserGate.maxGate;
        var currGateObj = gateList[currGatePos];
        if (currGateObj) {
          that.setData({
            currGateId: currGateObj.id,
            gateTGotalSize: gateList.length,
            currGateObj: currGateObj
          });
        }
      }else{

        this.getGateList()
      }
    } catch (e) {
      console.log(e)
    }

  },

    /**
   * 获取关卡集合
   */
  getGateList: function() {
    var that = this;
    wx.request({
      url: config.getGameLevels,
      method: 'POST',
      data: {
        openId: app.globalData.openid
      },
      success: function (res) {
        // console.log(JSON.stringify(res.data));
        if (res.data.success == 0) {
        var data=res.rows;
        var gateList = data.miniGates;
        var currGatePos =gateList.miniUserGate.maxGate;
        console.log(currGatePos)
        var currGateObj = gateList[currGatePos];
        if (currGateObj) {
          that.setData({
            currGateId: currGateObj.id,
            gateTGotalSize: gateList.length,
            currGateObj: currGateObj
          });
        }
        } 
      },
      fail: function(){


      }
      
    });

  },

  //获取10条问题
  getQuestionList: function () {
    var that = this;
    wx.request({
      url: config.getQuestionAndAnswerByGateId,
      method: 'POST',
      data: {
        gateId: that.data.currGateId
      },
      success: function (res) {
        console.log('res',res)
        if (res.data.success == 0) {
          that.setData({
            questionList: res.data.rows
          });
          that.getNextQuestion();
          //延迟1s给用户反应
          setTimeout(function () {
            //开启动画和定时器
            that.startProgressAnim();
            that.startTimer();

          }, 2000);

        }
      },

      fail: function (error) {
        console.log(error)
      }
    })
  },
  //获取下一个问题
  getNextQuestion: function () {

    currQuestion = this.data.questionList[index];
    var questionDesc = currQuestion.content;
    var answerList = currQuestion.answers;
    this.setData({
      currQuestion: currQuestion,
      questionDesc: questionDesc,
      answerList: answerList,
      isShowAnswer: false,
      currentQuestionPos: index
    })


  },

  //选择答案点击事件
  selectedCase: function (event) {
    var that = this;
    console.log(this.data.isShare+this.data.times)
    if (that.data.isShowAnswer) {
      //如果已经显示答案，不能再次选择答案
      return;
    }
    //获取选择id
    var answerid = event.currentTarget.dataset.answerid;
    var correct = event.currentTarget.dataset.correct;
    console.log("answerid=" + answerid + "correct=" + correct)
    //计算用户答对了几道题
    var count = that.data.rightCount + 1;
    if (correct == 1) {
      console.log("计算用户答对了几道题" + count);
      that.setData({
        rightCount: count
      });
    }

    that.setData({
      isShowAnswer: true,
      answerid: answerid,
      isAnswerRight: correct == 1
    });
    //保存数据 等10道题全部结束 统一提交
    var answerObj = {};
    answerObj.qid = that.data.currQuestion.id;
    answerObj.aid = answerid;
    answerObj.right = correct == 1 ? 0 : 1;
    that.data.answersData.push(answerObj);

    that.pauseTimer();
    clearInterval(varName);

    //如果答错了 就不在继续了 显示一个mode
    if (!that.data.isAnswerRight) {
      that.setData({
        //  闯关状态 0失败 1成功
        status: 0
      });
      //向服务器提交答案 
      that.setDataAndPost(correct);
      setTimeout(function () {
        wx.setNavigationBarColor({
          frontColor: '#ffffff',
          backgroundColor: '#FC7F63',
        })
        // 开始下一题
        that.showErrorDialog();
      }, 2000);

      return;
    }
    //通过当前关卡 显示继续答题ialog  如果不是最后一关
    if (index == this.data.questionList.length - 1) {
      if (that.data.currGatePos == that.data.gateTGotalSize - 1) {
        that.allGateThrough();
      } else {
        //有奖励和无奖励是不同的弹出框
        if (that.data.currGateObj.anyPrize == 1) {
          //anyPrize	有无奖品  2 无  1有 int 
          that.showThroughDialog();
        } else {
          that.showThroughNoDialog();
        }
      }

      var currGatePos = that.data.currGatePos;
      that.setData({
        currGatePos: currGatePos + 1,
        // 闯关状态 0失败 1成功
        status: 1
      });
      //向服务器提交答案 
      that.setDataAndPost(correct);

      return;
    }
    index++;
    if (index != that.data.questionList.length) {
      setTimeout(function () {
        // 开始下一题
        that.startNextQuestion();
      }, 2000);

    }

  },


  //设置缓存 并且向服务器提交答案
  setDataAndPost: function (correct) {
    var that = this;
    //用户答到最后一题 提交数据
    that.postAnserDataToServer();

  },




  //开始下一题的答题
  startNextQuestion: function () {
    var that = this;
    //自动跳转到下一题
    setTimeout(function () {
      console.log("下一题开始了！！！！！");
      that.getNextQuestion();
      that.startTimer();
      that.startProgressAnim();
    }, 2000);

  },

  //时间到自动显示答案 用户没有点击行为 
  autoShowCase: function () {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#FC7F63',
    })
    if (this.data.isShowAnswer) {
      //如果已经显示答案，不能再次选择答案
      return;
    }
    this.setData({
      isShowAnswer: true,
      answerid: -1,
      isAnswerRight: false

    })
    //设置缓存 并且向服务器提交答案
    //保存数据 等10道题全部结束 统一提交
    var answerObj = {};
    answerObj.qid = this.data.currQuestion.id;
    answerObj.right = 1;
    this.data.answersData.push(answerObj);

    //如果答错了 就不在继续了 显示一个mode
    if (!this.data.isAnswerRight) {
      this.setData({
        //  闯关状态 0失败 1成功
        status: 0
      });
      this.setDataAndPost(-1);
      this.showErrorDialog();
      return;
    }
    if (index < this.data.questionList.length) {
      // 开始下一题
      this.startNextQuestion();
    }


  },

  // 开始倒计时
  startTimer: function () {
    this.setData({
      time: 0
    });
    this.countDownd();

  },

  // 自定义的暂停按钮  
  pauseTimer: function () {
    console.log("定时任务停止");
    if (timer) {
      clearTimeout(timer);
    }

  },

  // 倒计时
  countDownd: function () {
    var that = this;
    timer = setTimeout(function () {
      var currTime = that.data.time + 1;
      console.log("----Countdown----" + currTime);
      that.setData({
        time: currTime
      });

      if (currTime == that.data.totalTime) {
        //当时间到达20秒 结束计时
        that.pauseTimer();
        if (!that.data.isShowAnswer) {
          //自动显示答案
          that.autoShowCase();

        } else {
          console.log("currentIndex===" + index)
          // if (index != that.data.questionList.length) {
          //   // 开始下一题
          //   that.startNextQuestion();
          // }

        }
      } else {
        that.countDownd();
      }
    }, 1000);
  },

  /**
   * 向服务器提交本轮答案
   */
  postAnserDataToServer: function () {
    var that = this;
    wx.request({
      url: config.postThroughAnswer,
      method: "POST",
      data: {
        // 一站到底
        openid: app.globalData.openid,
        status: that.data.status,
        gateId: that.data.currGateId,
        answers: that.data.answersData
      },
      success: function (res) {
        if (res.data.success == 0) {
        }
      },

      fail: function (error) {
        console.log(error)
      }

    })


  },


  /**
   * 画默认的圆形
   */
  drawDefaultArc: function () {
    //创建并返回绘图上下文context对象。
    var cxt_arc = wx.createCanvasContext('canvasCircle');
    cxt_arc.setLineWidth(3);
    cxt_arc.setStrokeStyle('#e2e2e2');
    cxt_arc.setLineCap('round');
    cxt_arc.beginPath();

    cxt_arc.arc(40, 40, 25, 0, 2 * Math.PI, false);

    cxt_arc.stroke();
    cxt_arc.draw();
  },

  drawArc: function (s, e) {
    var x = 40, y = 40, radius = 25;
    ctx.setLineWidth(3);
    ctx.setStrokeStyle('#ff6600');

    ctx.setLineCap('round');
    ctx.beginPath();
    ctx.arc(x, y, radius, s, e, false);
    ctx.stroke()
    ctx.draw()
  },

  /**
   *开启度条
   */
  startProgressAnim: function () {
    clearInterval(varName);
    var that = this;
    var step = 1, startAngle = 0.5 * Math.PI, endAngle = 0;
    var animation_interval = 200, n = that.data.totalTime * 1000 / 200;
    var animation = function () {
      if (step <= n) {
        endAngle = step * 2 * Math.PI / n + 0.5 * Math.PI;
        that.drawArc(startAngle, endAngle);
        step++;
      } else {
        clearInterval(varName);
      }
    };
    varName = setInterval(animation, animation_interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //当页面卸载时 停止定时任务
    this.pauseTimer();
  },

  /**
   * 弹窗
   */
  showErrorDialog: function () {
    this.setData({
      ansError: true
    })
    this.hiddenCircle();
  },
  showThroughDialog: function () {
    this.setData({
      isThrough: true
    })
    this.hiddenCircle();
  },

  showThroughNoDialog: function () {
    this.setData({
      isThroughNo: true
    })
    this.hiddenCircle();
  },
  /**
   * 弹出框蒙层截断touchmove事件
   */
  preventTouchMove: function () {
  },
  /**
   * 隐藏错误dialog 
   */
  hideErrorDialog: function () {
    this.setData({
      ansError: false
    });
  },
  /**
 * 隐藏潼关dialog
 */
  hideThroughDialog: function () {
    this.setData({
      isThrough: false
    });
  },

  hideThroughNoDialog: function () {
    this.setData({
      isThroughNo: false
    });
  },

  /**
   * 对话框取消按钮点击事件
   */
  onCancel: function () {
    this.hideModal();
    this.hideModal1();
  },
  /**
   * 对话框确认按钮点击事件
   */
  onConfirm: function () {
    this.hideModal();
    this.hideModal1();
  },

  /**
  * 返回首页
  */
  backTo: function (e) {
    wx.navigateBack({
      delta: -1
    });

  },

  /**
   * 显示全部通关
   */
  allGateThrough: function () {
    this.setData({
      isAllThrough: true
    });
    this.hiddenCircle();
  },

  /**
   * 继续闯关
   */
  ToNextLevel: function () {
    //初始化
    index = 0;
    this.getCurrGateId();
    this.getQuestionList();
    this.hideThroughNoDialog();
    this.showCirCle();

    var that = this;
    wx: wx.request({
      url: config.isCanPlay,
      data: {
        openId: app.globalData.openid
      },
      method: 'POST',
      success: function (res) {
        console.log(config.isCanPlay)
        console.log(JSON.stringify(res.data));
        that.setData({
          times: res.data.rows.remainTimes,
          isShare: res.data.rows.haveShared
        })
      }
    })
    wx.redirectTo({
      url: '../../loading/loading?fromType=2&times=' + this.data.times + '&isShare=' + this.data.isShare
    })
  },
  goToNextLevel: function () {
    //初始化
    var times = this.data.times-1;
    index = 0;
    this.getCurrGateId();
    this.getQuestionList();
    this.hideThroughDialog();
    this.showCirCle();
   
      var that = this;
      wx: wx.request({
        url: config.isCanPlay,
        data: {
          openId: app.globalData.openid
        },
        method: 'POST',
        success: function (res) {
          console.log(config.isCanPlay)
          console.log(JSON.stringify(res.data));
          that.setData({
            times: res.data.rows.remainTimes,
            isShare: res.data.rows.haveShared
          })
        }
      })
    wx.redirectTo({
      url: '../../loading/loading?fromType=2&times=' + times+ '&isShare=' + this.data.isShare
    })
  },
  
  hiddenCircle: function () {
    this.setData({
      isHidden: true
    });
  },
  showCirCle: function () {
    this.setData({
      isHidden: false
    });
  },
  /**
 * 通关领奖
 */
  toReceive: function (e) {
    wx: wx.request({
      url: config.toRecever,
      data: {
        gateId: this.data.currGateId,
        openId: app.globalData.openid
      },
      method: 'POST',
      success: function (res) {
        if (res.data.success == 0) {
          console.log(config.toRecever)
          console.log(JSON.stringify(res))
          wx.redirectTo({
            url: '../../games/receiveAward/receiveAward',
          })
        }
      },
    })
  },


  /**
  * 邀请好友
  */
  onShareAppMessage: function (res) {
    var that=this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    wx: wx.request({
        url: config.getOneChance,
        data: {
          openId: app.globalData.openid
        },
        method: 'POST',
        success: function (res) {
        	if (res.data.success == 0) {
                if (res.data.rows != 1) {
        	        if (!that.data.ansError&&that.data.isShare==0){
        	          that.data.times = parseInt(that.data.times)+1;
        	          that.data.isShare=1
        	          console.log(that.data.isShare)
        	        }
                }
              }
        }, 

      })
    	
   
    return {
      title: app.globalData.userInfo.nickName + '邀请你答题闯关！',
      // path: "pages/games/throughGame/throughGame",
      path: '../../../../pages/index/index?pageId=' + config.throughGame,
      success: function (res) {
       
      }
    }
  }
})